//
//  SettingTurnLastStepViewController.m
//  SIqICalendar
//
//  Created by SKiran on 17/3/2.
//  Copyright © 2017年 sjw. All rights reserved.
//

#import "SettingTurnLastStepViewController.h"
#import "JWCalendarModel.h"
#import "ConfirmTurnCalendar.h"
#import "JWCalendarViewController.h"
#import "JWRealmManager.h"

@interface SettingTurnLastStepViewController ()<ConfirmTurnCalendarViewDelegate>

@end

@implementation SettingTurnLastStepViewController
{
    UILabel     *_titleLabel;
    UIView      *_selectTurnBgView;
    CGFloat      _selectTurnHeight;
    ConfirmTurnCalendar *_calendarView;
    BOOL            _isdefault;
    NSDate           *_theTurnFirstDate;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initalTitleView];
    
    [self initialData];
    
    [self createView];
}

- (void)initialData {
    _selectTurnHeight = WGiveHeight(30);
    if (self.calendarModel) {
        _isdefault = self.calendarModel.isDefault.boolValue;
        _theTurnFirstDate = self.calendarModel.firstDate;
    }else {
        if ([JWCalendarModel allObjects].count == 0) {
            _isdefault = YES;
        }else {
            _isdefault = NO;
        }
    }
    
}

- (void)createView {
    
    UIView  *lineV = [[UIView alloc]init];
    lineV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:lineV];
    
    CGFloat leftMargin = WGiveWidth(30.f);
    CGFloat topMargin = WGiveHeight(150.f);
    CGFloat lineVWidth = kScreenWidth - 2*leftMargin;
    [lineV makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftMargin);
        make.width.equalTo(lineVWidth);
        make.height.equalTo(2);
        make.top.equalTo(self.view.top).equalTo(topMargin);
    }];
    
    // 说明label
    UILabel *notesLabelInTop = [[UILabel alloc]init];
    notesLabelInTop.text = @"请按照排班表的顺序选择日历的第一天吧👇";
    notesLabelInTop.textColor = UIColorFromRGB(0xCCCCCC);
    notesLabelInTop.font = [UIFont systemFontOfSize:defaultFont];
    notesLabelInTop.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:notesLabelInTop];
    
    [notesLabelInTop makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(0);
        make.top.equalTo(lineV.bottom).offset(WGiveHeight(10));
    }];
    
    _selectTurnBgView = [[UIView alloc]init];
    _selectTurnBgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_selectTurnBgView];
    
    [_selectTurnBgView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lineV.top).offset(5);
        make.centerX.equalTo(self.view.centerX);
        make.height.equalTo(WGiveHeight(60));
    }];
    CGFloat margin = 10;
    for (int i = 0 ; i < _currentSelectTurnDatas.count; i++) {
        JWScheduleModel *model = [self.currentSelectTurnDatas objectAtIndex:i];
        // 添加
        UILabel *turnLabel = [[UILabel alloc]init];
        turnLabel.backgroundColor = model.scheduleColor;
        turnLabel.text = model.scheduleName;
        turnLabel.textColor = [UIColor whiteColor];
        turnLabel.font = [UIFont boldSystemFontOfSize:20.f];
        turnLabel.textAlignment = NSTextAlignmentCenter;
        turnLabel.layer.masksToBounds = YES;
        [turnLabel setAdjustsFontSizeToFitWidth:YES];
        turnLabel.layer.cornerRadius = _selectTurnHeight/2.0;
        [_selectTurnBgView addSubview:turnLabel];
        [turnLabel makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_selectTurnBgView.centerY);
            make.height.equalTo(_selectTurnHeight);
            make.width.equalTo(_selectTurnHeight);
            make.left.equalTo(i * (margin + _selectTurnHeight));
        }];
    }
    
    [_selectTurnBgView updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo((_currentSelectTurnDatas.count) * (margin + _selectTurnHeight));
    }];
    
    // 选择日历
    _calendarView = [[ConfirmTurnCalendar alloc]initWithFrame:CGRectMake(0, kScreenHeight - WGiveHeight(360), kScreenWidth, WGiveHeight(360)) withCurrentSelectTurnDatas:self.currentSelectTurnDatas andTurnModel:self.calendarModel andDelegate:self];
    _calendarView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:_calendarView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveAction)];
}

- (void)initalTitleView {
    
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont systemFontOfSize:CalendarTitleFont];
    _titleLabel.textColor = TitleColor;
    _titleLabel.text = self.isEdit ? @"编辑排班（3/3）" : @"创建排班（3/3）";
    
    self.navigationItem.titleView = _titleLabel;
}

- (void)saveAction {
    
    if (!_theTurnFirstDate) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"请点击日历选择倒班的第一天" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    RLMArray *scheduleDatas = [[RLMArray alloc]initWithObjectClassName:JWScheduleModel.className];
    
    for (JWScheduleModel *model1 in self.currentSelectTurnDatas) {
        [scheduleDatas addObject:model1];
    }
    
    JWCalendarModel *turnModel = [[JWCalendarModel alloc]init];
    turnModel.firstDate = _theTurnFirstDate;
    turnModel.scheduleStatus = scheduleDatas;
    turnModel.calendarName = self.turnName;
    turnModel.isDefault = @(_isdefault);
    turnModel.orderIndex = @([JWRealmManager defaultManager].numberOfCalendars);

    
    if (self.isEdit) {
        turnModel.calendarId = self.calendarModel.calendarId;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清空当前日历中的串班信息？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *stilAction = [UIAlertAction actionWithTitle:@"保留" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 更新
            turnModel.exchangedDate = self.calendarModel.exchangedDate;
            
            [[JWRealmManager defaultManager] addOrUpdateWithJWCalendarModel:turnModel];
            
            [self handleAfterSave];
        }];
        
        UIAlertAction *clearAction = [UIAlertAction actionWithTitle:@"清空" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            // 更新
            turnModel.exchangedDate = @"";
            
            [[JWRealmManager defaultManager] addOrUpdateWithJWCalendarModel:turnModel];
            [self handleAfterSave];
        }];
        
        [alertController addAction:stilAction];
        [alertController addAction:clearAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        // 新建
        turnModel.exchangedDate = @"";
        
        [[JWRealmManager defaultManager] insertWithJWCalendarModel:turnModel];
        
        if ([JWRealmManager defaultManager].numberOfCalendars == 0) {
            [PublicData sharedInstance].currentSelectedCalendarId = turnModel.calendarId;
        }
        [self handleAfterSave];
        
    }
}

- (void)handleAfterSave {
    [[NSNotificationCenter defaultCenter] postNotificationName:JWCalendarAfterCreatedOrUpdatedNotification object:nil];
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[JWCalendarViewController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
        }
    }
}

- (void)didSelectTheFirstDate:(NSDate *)theFirstDate {
    _theTurnFirstDate = theFirstDate;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
